/**
 *
 */
package com.whosly.rapid.lang.thread.support;

import com.whosly.api.constant.ConventionsX;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import com.whosly.rapid.lang.thread.model.InheritableEntity;

/**
 * 线程间通信
 *
 * @author yueny09 <yueny09@163.com>
 *
 * @DATE 2017年11月11日 下午6:18:49
 *
 */
public class InheritableThreadHolder {
	/**
	 * 持有的当前线程的上下文信息
	 */
	private static final InheritableThreadLocalExt holder = new InheritableThreadLocalExt();

	/**
	 * 从LOG的上下文里取出LOGID
	 */
	private static void fillCommonContents(final InheritableEntity entity) {
		final String logId = MDC.get(ConventionsX.CTX_LOG_ID_MDC);
		if (StringUtils.isNotBlank(logId)) {
			entity.setLogId(logId);
			entity.setParentThreadId(Thread.currentThread().getId());
		}
	}

	/**
	 * 获得目前的上下文
	 *
	 * @return 目前的上下文
	 */
	public static InheritableEntity get() {
		InheritableEntity entity = holder.get();
		if (entity == null) {
			init();
			entity = holder.get();
		}
		return entity;
	}

	/**
	 * 清理旧的内容
	 */
	private static void init() {
		holder.remove();
		holder.set(InheritableEntity.builder().build());

		fillCommonContents(holder.get());
	}

	/**
	 * 移除上下文
	 */
	public static void remove() {
		holder.remove();
	}

}
